const {Catalog} = require('../../mongodb/models')
const {getUserByCtx} = require('../../utils/common')

module.exports = [
	{
		path: '/catalog',
		method: 'post',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			var catalogIsExist = await Catalog.findOne({
				name: ctx.request.body.name,
				userId: _id,
				projectId: ctx.request.body.projectId,
			})
			if(catalogIsExist){
				ctx.response.body = {
					errCode: 1,
					errMsg: '目录已存在'
				}
			}else{
				var count = await Catalog.countDocuments({userId: _id, projectId: ctx.request.body.projectId}) + 1
				var doc = await Catalog.create({name: ctx.request.body.name, userId: _id, projectId: ctx.request.body.projectId, sort: count})
				ctx.response.body = {
					errCode: doc ? 0 : -1,
					errMsg: doc ? '创建成功' : '创建失败',
					data: doc
				}
			}
		}
	},{
		path: '/catalog/:projectId',
		method: 'get',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			var docs = await Catalog.find({userId: _id, projectId: ctx.params.projectId}, (err, docs)=>docs)
			ctx.response.body = {
				errCode: docs ? 0 : -1,
				errMsg: docs ? 'request:success' : '项目获取失败',
				data: docs
			}
		}
	},{
		path: '/catalog/:id',
		method: 'put',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			const doc = await Catalog.updateOne({userId: _id, _id: ctx.params.id}, {name: ctx.request.body.name})
			ctx.response.body = {
				errCode: doc.nModified ? 0 : -1,
				errMsg: doc.nModified ? 'request:success' : '目录修改失败',
				data: doc
			}
		}
	},{
		path: '/catalog/move/:id/:id2',
		method: 'put',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			const doc = await Catalog.updateOne({userId: _id, _id: ctx.params.id}, {sort: ctx.request.body.sort})
			Catalog.updateOne({userId: _id, _id: ctx.params.id2}, {sort: ctx.request.body.sort2}, (err, doc)=>{
				console.log(doc)
			})
			ctx.response.body = {
				errCode: doc.nModified ? 0 : -1,
				errMsg: doc.nModified ? 'request:success' : '目录排序失败',
				data: doc
			}
		}
	},{
		path: '/catalog/:id',
		method: 'delete',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			const doc = await Catalog.deleteOne({userId: _id, _id: ctx.params.id})
			ctx.response.body = {
				errCode: doc ? 0 : -1,
				errMsg: doc ? '删除成功' : '删除失败',
				data: doc
			}
		}
	},{
		path: '/catalogList',
		method: 'get',
		process: async (ctx, next) => {
			const docs = await Catalog.find({projectId:ctx.query.projectId})
			ctx.response.body = {
				errCode: docs ? 0 : -1,
				errMsg: docs ? 'request:success' : '目录获取失败',
				data: docs
			}
		}
	}
]